<script setup>
import { reactive, ref, toRaw, watch } from "vue";

import { createClient, updateClient } from "@/api/client";
import MQTTClientItem from "./MQTTClientItem.vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  data: {
    type: Object,
    default: null
  }
})
const emits = defineEmits(["submit"])

const visible = defineModel("visible")
const clientType = ref("MQTT")
const srcName = ref()  // 缓存客户端修改前的名称
const mqttInfo = reactive({
  name: '',
  clientId: '',
  host: '',
  port: 1883,
  comType: "mqtt",
  username: '',
  password: '',
  willTopic: "",
  willPayload: "",
  willQoS: 0,
  willRetain: false
})
const httpInfo = reactive({})
const wsInfo = reactive({})
const clientInfo = {
  MQTT: mqttInfo,
  HTTP: httpInfo,
  WebSocket: wsInfo
}

watch(() => props.data, val => {
  if (!val) {
    srcName.value = null
    return
  }
  clientType.value = val.type
  if (val.type === 'MQTT') {
    delete val.type
    Object.assign(mqttInfo, val)
    srcName.value = val.name
  }
})

function submit() {
  if (props.data) {
    updateClient(srcName.value, toRaw(clientInfo[clientType.value])).then(res => {
      if (res.code === 200) {
        visible.value = false
        ElMessage.success("修改成功")
        emits("submit")
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      console.log(err)
      ElMessage.error("网络异常，请稍后重试")
    })
  } else {
    createClient(clientType.value, clientInfo[clientType.value]).then(res => {
      if (res.code === 200) {
        visible.value = false
        ElMessage.success("创建成功")
        emits("submit")
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      console.log(err)
      ElMessage.error("网络异常，请稍后重试")
    })
  }
}
</script>

<template>
	<el-dialog v-model="visible" :title="props.data ? `${props.data.name} 详细信息` : '创建客户端'">
    <el-form label-width="96px" label-position="right" style="margin-right: 24px;">
      <el-form-item label="名称">
        <el-input v-model="clientInfo[clientType].name" />
      </el-form-item>
      <el-form-item label="类型">
        <el-radio-group v-model="clientType">
          <el-radio label="MQTT">MQTT</el-radio>
          <el-radio label="HTTP">HTTP</el-radio>
          <el-radio label="WebSocket">WebSocket</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- MQTT客户端选项 -->
      <div v-if="clientType === 'MQTT'">
        <MQTTClientItem :info="clientInfo.MQTT" />
      </div>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped lang="scss">
</style>